package com.sykj.fileupload.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.MultipartConfigElement;

@Configuration
public class UploadConfig extends WebMvcConfigurerAdapter {
    @Value("${file.uploadPath}")
    private String uploadPath;

    /**
     * 配置静态资源访问
     */
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/","classpath:/ueditor/"};

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST").allowCredentials(true).maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
        registry.addResourceHandler("/files/**")
//                .addResourceLocations("file:////home/files/");
                .addResourceLocations("file:///"+uploadPath);
        super.addResourceHandlers(registry);
    }



    // 配置上传文件大小限制  配置文件和配置类 任选其一即可

    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory=new MultipartConfigFactory();
        // 文件最大
        factory.setMaxFileSize("5000MB");
        factory.setMaxRequestSize("5000MB");
        return factory.createMultipartConfig();
    }



}
